package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.constant.RedisKeyConstant;
import com.sky.constant.StatusConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 处理订单的定时任务
 */
@Component
@Slf4j
public class HandleOrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 处理支付超时订单：每两分钟执行一次
     * 需求：如果下单后超过15分钟就未支付，则取消该订单
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void handlePayTimeoutOrder(){
        log.info("处理支付超时订单");
        Integer status = Orders.PENDING_PAYMENT;
        // 获取当前时间并减去15分钟
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.getBySTatusAndOrderTimeOut(status, time);
        for(Orders item : ordersList){
            item.setStatus(Orders.CANCELLED);
            item.setCancelTime(LocalDateTime.now());
            item.setCancelReason(MessageConstant.ORDER_PAYMENT_FAILED);
            orderMapper.update(item);
        }
    }

    /**
     * 处理已完成订单：每一小时执行一次
     * 需求：如果商家已打样,"派送中"就等候一小时自动完成订单
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void handleCompletedOrder(){
        log.info("处理已完成订单");
        // 获取商家店铺状态
        Object status = redisTemplate.opsForValue().get(RedisKeyConstant.KEY);
        // 如果状态不等于1说明已经打烊了
        if(status != StatusConstant.ENABLE && status != null){
            Integer orderStatus = Orders.DELIVERY_IN_PROGRESS;
            LocalDateTime time = LocalDateTime.now().minusHours(1); // 获取当前时间并减去1小时
            List<Orders> ordersList = orderMapper.getBySTatusAndOrderTimeOut(orderStatus, time);
            for(Orders item : ordersList){
                item.setStatus(Orders.COMPLETED);
                item.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(item);
            }
        }
    }
}
